package hhs.scannerapp;

import java.io.File;
import java.io.IOException;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.Toast;

public class EmailActivity extends Activity 
{
	private ProgressBar pBar;
	private EditText emailText; 
	private String ext;
	private File f = null;
	private File dir;

	//runs when activity is called
	public void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.email_layout); 
		emailText = (EditText)findViewById(R.id.email_text);
		pBar = (ProgressBar)findViewById(R.id.progress);


		//event listener for send button
		OnClickListener sendListener = new OnClickListener()
		{
			public void onClick(View arg0) 
			{         	
				sendEmail();
			}
		};  
		Button send = (Button) findViewById(R.id.b_send);
		send.setOnClickListener(sendListener);

		//event listener for clear button - sets email back to default
		OnClickListener clearListener = new OnClickListener()
		{
			public void onClick(View arg0) 
			{         	
				emailText.setText("");
			}
		};  
		Button clear = (Button) findViewById(R.id.clear_button);
		clear.setOnClickListener(clearListener);	
	}


	//calls instance of MailOp class to send the calls through email
	public void sendEmail()
	{
		pBar.setVisibility(View.VISIBLE);  

		if(checkForConfiguredEmail())  //set in Convert after checking external writable memory which is needed to attached a document using email widget
		{
			try 
			{
				Intent i = new Intent(Intent.ACTION_SEND);
				i.setType("message/rfc822");
				i.putExtra(Intent.EXTRA_EMAIL, new String[]{emailText.getText().toString()});
				i.putExtra(Intent.EXTRA_SUBJECT, "Model from Exact3DExtract");
				i.putExtra(Intent.EXTRA_TEXT   , "See attachment");
										
				Uri uri = Uri.fromFile(f);
				i.putExtra(Intent.EXTRA_STREAM, uri);
				startActivityForResult(i,1);	
			}
			//catches if there is external memory but no email configured on device.
			catch(android.content.ActivityNotFoundException ex) 
			{
				Toast.makeText(EmailActivity.this, "There are no email clients installed on your device.", Toast.LENGTH_LONG).show();
				Toast.makeText(EmailActivity.this, "Until you configure email on this device, these emails will be sent from a default email account.", Toast.LENGTH_LONG).show();
				//sends using default gmail account
				new MailOp(f,emailText.getText().toString(), "Model from Exact3DExtract", "See attachment").execute();
			}
		}
		else
		{
			//uses default gmail account
			new MailOp(f, emailText.getText().toString(), "Model from Exact3DExtract", "See attachment").execute(); 
		}
	}

	//gets called after startActivityForResult - used to tell when email has been sent
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		pBar.setVisibility(View.INVISIBLE); 
	}
	
	public boolean checkForConfiguredEmail()
	{
		Context context = getBaseContext();
		boolean mExternalStorageWriteable = false;
		String state = Environment.getExternalStorageState();
		
		//checks for external storage on device
		if (Environment.MEDIA_MOUNTED.equals(state))
		{
			mExternalStorageWriteable = true;
		} 
		else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) 
		{
			mExternalStorageWriteable = false;
			Toast.makeText(context,"External storage is set to read only. Email will be sent from default gmail account.", Toast.LENGTH_LONG).show();
		} 
		else 
		{
			mExternalStorageWriteable = false;
			Toast.makeText(context,"Not able to read or write to external storage. Email will be sent from default gmail account.", Toast.LENGTH_LONG).show();
		}
		//sets flag to send either using widget or default gmail account
		if(mExternalStorageWriteable)
		{
			Spinner sp = (Spinner) findViewById(R.id.i_format_sp);
			String type = (String)sp.getSelectedItem();
			
			if("OBJ".equals(type))
			{
				ext = ".obj";
			}
			else if("PDF".equals(type))
			{
				ext = ".pdf";
			}
			else
			{
				ext = ".stl";
			}
			f = new File(Environment.getExternalStorageDirectory() + "/Models/model" + ext);
			return true;
		}
		else
		{ 
			dir = context.getFilesDir();
			try 
			{
				f = File.createTempFile("model", ext, dir);
			} 
			catch (IOException e) 
			{
				e.printStackTrace();
			}
			return false;
		}
	}
	
	//private internal MailOp class
	private class MailOp extends AsyncTask<Void, Integer, String> 
	{
		File send;
		String email;
		String subject;
		String message;
	
		//sets data fields with sent in values
		public MailOp(File sen, String emai, String subjec, String messag)
		{
			send = sen;
			email = emai;
			subject = subjec;
			message = messag;
		}
	
		//does in background so other events can happen on device
		@Override
		protected String doInBackground(Void...values) 
		{
			try
			{
				//sends email from Mail class
				if(Mail.send(new String[]{email},subject,message,send,"calls"))
				{
					return "Email successfully sent to " + email + ".";
				}
				else
				{
					return "Email failed to be sent.";
				}
			}
			catch(Exception e)
			{
				return e.getClass().getSimpleName();
			}   
		}      
	
		//when done sending email progress bar becomes invisible again
		@Override
		protected void onPostExecute(String result) 
		{       
			pBar.setVisibility(View.INVISIBLE); 
			Toast.makeText(getBaseContext(), result, Toast.LENGTH_LONG).show();
		}
	
		@Override
		protected void onProgressUpdate(Integer... values) 
		{
			super.onProgressUpdate(values);
		}
	}
}

